'use client';

import React, { useState, useEffect, useRef, forwardRef, useCallback } from 'react';
import { request } from '@/utils/request';

interface CosVideoWithProgressProps extends React.VideoHTMLAttributes<HTMLVideoElement> {
  path: string;
  courseId: number;
  chapterId: number;
  userId: number;
  onProgressUpdate?: (progress: number) => void;
  initialProgress?: number;
}

export const CosVideoWithProgress = forwardRef<HTMLVideoElement, CosVideoWithProgressProps>(
  ({ path, courseId, chapterId, userId, onProgressUpdate, initialProgress = 0, ...props }, ref) => {
    const [url, setUrl] = useState('');
    const [error, setError] = useState<string | null>(null);
    const videoRef = useRef<HTMLVideoElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const [currentProgress, setCurrentProgress] = useState(initialProgress);
    const [isTracking, setIsTracking] = useState(false);
    const progressUpdateTimer = useRef<NodeJS.Timeout | null>(null);

    console.log(path,'pathpath')




   

  

    // 处理视频播放开始
    const handlePlay = useCallback(() => {
      setIsTracking(true);
      
      // 记录播放事件
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;
      if (video) {
        // 记录学习进度到后端
        try {
          request(`/courses/${courseId}/chapters/${chapterId}/progress`, {
            method: 'POST',
            body: JSON.stringify({ progress: 0 })
          });
        } catch (error) {
          console.error('记录播放事件失败:', error);
        }
      }
    }, [courseId, chapterId, userId, ref]);

    // 处理视频播放进度更新
    const handleTimeUpdate = useCallback(() => {
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;
      if (video && isTracking && video.duration > 0) {
        const currentProgress = (video.currentTime / video.duration) * 100;
        setCurrentProgress(currentProgress);
        onProgressUpdate?.(currentProgress);
        
        // 每10秒更新一次进度到后端
        if (progressUpdateTimer.current) {
          clearTimeout(progressUpdateTimer.current);
        }
        
        progressUpdateTimer.current = setTimeout(async () => {
          try {
            await request(`/courses/${courseId}/chapters/${chapterId}/progress`, {
              method: 'POST',
              body: JSON.stringify({ progress: Math.round(currentProgress) })
            });
          } catch (error) {
            console.error('更新学习进度失败:', error);
          }
        }, 10000);
      }
    }, [courseId, chapterId, isTracking, onProgressUpdate, ref]);

    // 处理视频结束
    const handleEnded = useCallback(() => {
      setIsTracking(false);
      setCurrentProgress(100);
      onProgressUpdate?.(100);
      
      // 记录视频结束事件
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;
      if (video) {
        // 记录视频结束事件
        try {
          request(`/courses/${courseId}/chapters/${chapterId}/progress`, {
            method: 'POST',
            body: JSON.stringify({ progress: 100 })
          });
        } catch (error) {
          console.error('记录视频结束事件失败:', error);
        }
      }
    }, [courseId, chapterId, userId, onProgressUpdate, ref]);

    // 设置视频事件监听器
    useEffect(() => {
      // 获取实际的video元素引用
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;

      if (!video) return;

      video.addEventListener('play', handlePlay);
      video.addEventListener('ended', handleEnded);
      video.addEventListener('timeupdate', handleTimeUpdate); // 添加timeupdate监听器

      return () => {
        video.removeEventListener('play', handlePlay);
        video.removeEventListener('ended', handleEnded);
        video.removeEventListener('timeupdate', handleTimeUpdate); // 移除timeupdate监听器
      };
    }, [handlePlay, handleEnded, handleTimeUpdate, ref]);

    // 设置初始进度
    useEffect(() => {
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;
      if (video && initialProgress > 0) {
        // 根据进度设置播放位置
        video.addEventListener('loadedmetadata', () => {
          if (video.duration > 0) {
            video.currentTime = (initialProgress / 100) * video.duration;
          }
        }, { once: true });
      }
    }, [initialProgress, ref]);



    // 清理定时器
    useEffect(() => {
      return () => {
        if (progressUpdateTimer.current) {
          clearTimeout(progressUpdateTimer.current);
        }
      };
    }, []);

    // 监听全屏事件
    useEffect(() => {
      const video = (ref as React.MutableRefObject<HTMLVideoElement | null>)?.current || videoRef.current;
      const container = containerRef.current;
      if (!video || !container) return;
    
      function forceContainerFullscreen() {
        if ((document as any).webkitFullscreenElement === video) {
          (document as any).webkitExitFullscreen();
          if ((container as any).webkitRequestFullscreen) {
            (container as any).webkitRequestFullscreen();
          }
        }
        if ((document as any).mozFullScreenElement === video) {
          (document as any).mozCancelFullScreen();
          if ((container as any).mozRequestFullScreen) {
            (container as any).mozRequestFullScreen();
          }
        }
        if ((document as any).msFullscreenElement === video) {
          (document as any).msExitFullscreen();
          if ((container as any).msRequestFullscreen) {
            (container as any).msRequestFullscreen();
          }
        }
      }
    
      video.addEventListener('fullscreenchange', forceContainerFullscreen);
      video.addEventListener('webkitfullscreenchange', forceContainerFullscreen);
      video.addEventListener('mozfullscreenchange', forceContainerFullscreen);
      video.addEventListener('MSFullscreenChange', forceContainerFullscreen);
    
      return () => {
        video.removeEventListener('fullscreenchange', forceContainerFullscreen);
        video.removeEventListener('webkitfullscreenchange', forceContainerFullscreen);
        video.removeEventListener('mozfullscreenchange', forceContainerFullscreen);
        video.removeEventListener('MSFullscreenChange', forceContainerFullscreen);
      };
    }, []);

    // 自定义全屏按钮
    const handleFullscreen = () => {
      const container = containerRef.current;
      if (!container) return;
      const isFull =
        document.fullscreenElement === container ||
        (document as any).webkitFullscreenElement === container ||
        (document as any).mozFullScreenElement === container ||
        (document as any).msFullscreenElement === container;
      if (isFull) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if ((document as any).webkitExitFullscreen) {
          (document as any).webkitExitFullscreen();
        } else if ((document as any).mozCancelFullScreen) {
          (document as any).mozCancelFullScreen();
        } else if ((document as any).msExitFullscreen) {
          (document as any).msExitFullscreen();
        }
      } else {
        if (container.requestFullscreen) {
          container.requestFullscreen();
        } else if ((container as any).webkitRequestFullscreen) {
          (container as any).webkitRequestFullscreen();
        } else if ((container as any).mozRequestFullScreen) {
          (container as any).mozRequestFullScreen();
        } else if ((container as any).msRequestFullscreen) {
          (container as any).msRequestFullscreen();
        }
      }
    };

    if (error) return <div className="text-red-500">加载失败: {error}</div>;

    // 隐藏video原生全屏按钮
    const hideFullscreenStyle = `
      video::-webkit-media-controls-fullscreen-button { display: none !important; }
      video::-webkit-media-controls-enclosure { overflow: hidden; }
    `;

    // 水印样式
    const watermarkStyle: React.CSSProperties = {
      position: 'absolute',
      pointerEvents: 'none',
      zIndex: 100,
      color: isFullscreen ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.6)',
      fontSize: isFullscreen ? 20 : 24,
      fontWeight: 'bold',
      textShadow: '1px 1px 3px rgba(0,0,0,0.8)',
      opacity: isFullscreen ? 0.8 : 0.7,
      right: 16,
      top: 16,
      userSelect: 'none',
      transform: isFullscreen ? 'none' : 'rotate(-20deg)',
    };

    return (
      <div
        ref={containerRef}
        className="player-container"
        style={{
          position: 'relative',
          width: '100%',
          height: '100%',
          background: '#000',
          borderRadius: 10,
          overflow: 'hidden',
        }}
      >
        {/* 隐藏video原生全屏按钮的样式 */}
        <style>{hideFullscreenStyle}</style>
        <video
          ref={ref || videoRef}
          id="videoPlayer"
          className="w-full h-full rounded-lg"
          src={path}
          {...props}
          style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}
          controls
        />
        
        {/* 学习进度指示器 */}
        {/* {isTracking && (
          <div className="absolute top-4 left-4 z-50 bg-black/70 text-white px-3 py-1 rounded text-sm">
            学习进度: {Math.round(currentProgress)}%
          </div>
        )} */}
        
        {/* 自定义全屏按钮 */}
        <button
          type="button"
          onClick={handleFullscreen}
          style={{
            position: 'absolute',
            right: 16,
            bottom: 16,
            zIndex: 200,
            background: 'rgba(0,0,0,0.4)',
            color: '#fff',
            border: 'none',
            borderRadius: 4,
            padding: '6px 12px',
            cursor: 'pointer',
          }}
        >
          全屏
        </button>
        
        {/* 右上角水印 */}
        <div className="watermark" style={watermarkStyle}>
          不可外传
        </div>
      </div>
    );
  }
);

CosVideoWithProgress.displayName = 'CosVideoWithProgress'; 